package com.suxin.test.netty.adv.server;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.example.netty.adv.server.async.AsyncBusiProcess;
import org.example.netty.adv.server.async.ITaskProcessor;
import org.example.netty.adv.vo.Message;
import org.example.netty.adv.vo.MessageHeader;
import org.example.netty.adv.vo.MessageType;

/**
 * @Author: tang
 * @Description: server 业务处理 handler
 * @Date 2025/1/21 09:47
 */
@Slf4j
public class ServerBusiInBoundChannelHandler extends SimpleChannelInboundHandler<Message> {

    private final ITaskProcessor processor;
    public ServerBusiInBoundChannelHandler(ITaskProcessor processor) {
        this.processor = processor;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Message msg) throws Exception {
        MessageHeader messageHeader = msg.getMessageHeader();
        byte type = messageHeader.getType();
        // 需要业务应答
        if (type == MessageType.SERVICE_RESP.value()) {
            ctx.writeAndFlush(Message.buildSendTwoServerMsg("OK", messageHeader.getMsgId()));
        }else {
            AsyncBusiProcess.submitTask(this.processor.asyncRunnable(msg));
        }
    }
}
